//
//  BlackTextField.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/14.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

class BlackTextField: UITextField {
  
  private var tintedClearImage: UIImage?
  
  private func setupTintColor() {
    clearButtonMode = UITextField.ViewMode.whileEditing
    backgroundColor = .clear
    textColor = .white
  }
  
  private func tintClearImage() {
    for view in subviews {
      if view is UIButton {
        let button = view as! UIButton
        if let uiImage = button.image(for: .highlighted) {
          if tintedClearImage == nil {
            tintedClearImage = tintImage(image: uiImage, color: .gray)
          }
          button.setImage(tintedClearImage, for: .normal)
          button.setImage(tintedClearImage, for: .highlighted)
        }
      }
    }
  }
  
  private func tintImage(image: UIImage, color: UIColor) -> UIImage? {
    let size = image.size
    
    UIGraphicsBeginImageContextWithOptions(size, false, image.scale)
    let context = UIGraphicsGetCurrentContext()
    image.draw(at: CGPoint.zero, blendMode: .normal, alpha: 1.0)
    context!.setFillColor(color.cgColor)
    context!.setBlendMode(.sourceIn)
    context!.setAlpha(1.0)
    let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
    context!.fill(rect)
    let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return tintedImage
  }
  
  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setupTintColor()
  }
  
  override init(frame: CGRect) {
    super.init(frame: frame)
    setupTintColor()
  }
  
  override func layoutSubviews() {
    super.layoutSubviews()
    tintClearImage()
  }
  
  override func willMove(toSuperview newSuperview: UIView?) {
    super.willMove(toSuperview: newSuperview)
    
    if let p = placeholder {
      attributedPlaceholder = NSAttributedString(string: p, attributes: [ NSAttributedString.Key.foregroundColor: UIColor.gray])
    }
    textColor = .white
    keyboardAppearance = .dark
  }
}
